"use client"

import { useState } from "react"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Button } from "@/components/ui/button"
import { Badge } from "@/components/ui/badge"
import { Textarea } from "@/components/ui/textarea"
import { Label } from "@/components/ui/label"
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from "@/components/ui/dialog"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { 
  ArrowRight, 
  Upload, 
  FileText, 
  X, 
  CheckCircle,
  AlertTriangle,
  Clock,
  Target,
  Users,
  Activity
} from "lucide-react"
import { cn } from "@/lib/utils"

interface FlowTransition {
  id: string
  fromStatus: string
  event: string
  toStatus: string
  description: string
  requiresApproval: boolean
  requiresAttachment: boolean
  allowedRoles: string[]
}

interface FlowOperationProps {
  projectId: string
  currentStatus: string
  onFlowSubmit: (data: FlowSubmitData) => Promise<void>
}

interface FlowSubmitData {
  transitionId: string
  note: string
  description: string
  attachments: File[]
}

export default function FlowOperation({ projectId, currentStatus, onFlowSubmit }: FlowOperationProps) {
  const [selectedEvent, setSelectedEvent] = useState<string>("")
  const [selectedTransition, setSelectedTransition] = useState<FlowTransition | null>(null)
  const [note, setNote] = useState("")
  const [description, setDescription] = useState("")
  const [attachments, setAttachments] = useState<File[]>([])
  const [isSubmitting, setIsSubmitting] = useState(false)
  const [isDialogOpen, setIsDialogOpen] = useState(false)

  // 根据当前状态定义可用的流转选项
  const getAvailableTransitions = (): FlowTransition[] => {
    const baseTransitions: Record<string, FlowTransition[]> = {
      '草稿': [
        {
          id: 'draft_to_review',
          fromStatus: '草稿',
          event: '提交立项申请',
          toStatus: '待立项',
          description: '提交项目立项申请，进入董事长审核流程',
          requiresApproval: true,
          requiresAttachment: false,
          allowedRoles: ['业务员', '董事长']
        }
      ],
      '待立项': [
        {
          id: 'review_approved',
          fromStatus: '待立项',
          event: '审核通过',
          toStatus: '已立项',
          description: '董事长审核通过，项目正式立项',
          requiresApproval: false,
          requiresAttachment: false,
          allowedRoles: ['董事长']
        },
        {
          id: 'review_rejected',
          fromStatus: '待立项',
          event: '审核不通过',
          toStatus: '草稿',
          description: '董事长审核不通过，返回修改',
          requiresApproval: false,
          requiresAttachment: true,
          allowedRoles: ['董事长']
        }
      ],
      '已立项': [
        {
          id: 'assign_tasks',
          fromStatus: '已立项',
          event: '分配任务',
          toStatus: '设计中',
          description: '研发经理分配硬件/软件工程师和任务时间',
          requiresApproval: false,
          requiresAttachment: false,
          allowedRoles: ['研发经理']
        },
        {
          id: 'apply_dormancy',
          fromStatus: '已立项',
          event: '申请休眠',
          toStatus: '休眠',
          description: '项目暂时中止，进入休眠状态',
          requiresApproval: true,
          requiresAttachment: true,
          allowedRoles: ['业务员', '董事长']
        }
      ],
      '设计中': [
        {
          id: 'design_to_development',
          fromStatus: '设计中',
          event: '设计完成',
          toStatus: '开发中',
          description: '硬件设计完成，进入软件开发阶段',
          requiresApproval: true,
          requiresAttachment: true,
          allowedRoles: ['硬件工程师', '研发经理']
        },
        {
          id: 'design_dormancy',
          fromStatus: '设计中',
          event: '申请休眠',
          toStatus: '休眠',
          description: '设计阶段申请休眠',
          requiresApproval: true,
          requiresAttachment: true,
          allowedRoles: ['业务员', '董事长']
        }
      ],
      '开发中': [
        {
          id: 'development_to_test',
          fromStatus: '开发中',
          event: '开发完成',
          toStatus: '测试中',
          description: '软件开发完成，进入测试阶段',
          requiresApproval: true,
          requiresAttachment: true,
          allowedRoles: ['软件工程师', '研发经理']
        },
        {
          id: 'development_dormancy',
          fromStatus: '开发中',
          event: '申请休眠',
          toStatus: '休眠',
          description: '开发阶段申请休眠',
          requiresApproval: true,
          requiresAttachment: true,
          allowedRoles: ['业务员', '董事长']
        }
      ],
      '测试中': [
        {
          id: 'test_passed',
          fromStatus: '测试中',
          event: '测试通过',
          toStatus: '已完成',
          description: '测试通过，项目开发完成',
          requiresApproval: true,
          requiresAttachment: true,
          allowedRoles: ['测试组', '研发经理']
        },
        {
          id: 'test_failed',
          fromStatus: '测试中',
          event: '测试不通过',
          toStatus: '开发中',
          description: '测试发现问题，返回开发阶段修复',
          requiresApproval: false,
          requiresAttachment: true,
          allowedRoles: ['测试组']
        }
      ],
      '已完成': [
        {
          id: 'apply_order',
          fromStatus: '已完成',
          event: '申请订单',
          toStatus: '订单准备',
          description: '项目开发完成，申请进入生产流程',
          requiresApproval: true,
          requiresAttachment: true,
          allowedRoles: ['业务员', '董事长']
        },
        {
          id: 'project_archive',
          fromStatus: '已完成',
          event: '项目归档',
          toStatus: '已归档',
          description: '项目完成归档，结束项目生命周期',
          requiresApproval: true,
          requiresAttachment: false,
          allowedRoles: ['文控', '董事长']
        }
      ],
      '已归档': [
        {
          id: 'reactivate',
          fromStatus: '已归档',
          event: '重新激活',
          toStatus: '草稿',
          description: '重新激活已归档项目',
          requiresApproval: true,
          requiresAttachment: true,
          allowedRoles: ['董事长']
        }
      ]
    }

    return baseTransitions[currentStatus] || []
  }

  const availableTransitions = getAvailableTransitions()

  const handleEventChange = (eventId: string) => {
    setSelectedEvent(eventId)
    const transition = availableTransitions.find(t => t.id === eventId)
    setSelectedTransition(transition || null)
  }

  const handleFileUpload = (event: React.ChangeEvent<HTMLInputElement>) => {
    const files = Array.from(event.target.files || [])
    setAttachments(prev => [...prev, ...files])
  }

  const removeAttachment = (index: number) => {
    setAttachments(prev => prev.filter((_, i) => i !== index))
  }

  const handleSubmit = async () => {
    if (!selectedTransition) return

    setIsSubmitting(true)
    try {
      await onFlowSubmit({
        transitionId: selectedTransition.id,
        note,
        description,
        attachments
      })
      
      // 重置状态
      setSelectedEvent("")
      setSelectedTransition(null)
      setNote("")
      setDescription("")
      setAttachments([])
      setIsDialogOpen(false)
    } catch (error) {
      console.error('提交流转失败:', error)
    } finally {
      setIsSubmitting(false)
    }
  }

  const getStatusColor = (status: string) => {
    switch (status) {
      case '草稿': return 'bg-gray-500'
      case '待立项': return 'bg-yellow-500'
      case '已立项': return 'bg-blue-500'
      case '设计中': return 'bg-purple-500'
      case '开发中': return 'bg-indigo-500'
      case '测试中': return 'bg-orange-500'
      case '已完成': return 'bg-green-500'
      case '已归档': return 'bg-gray-600'
      case '休眠': return 'bg-gray-400'
      case '订单准备': return 'bg-teal-500'
      default: return 'bg-gray-500'
    }
  }

  const getEventIcon = (event: string) => {
    if (event.includes('审核')) return <CheckCircle className="h-4 w-4" />
    if (event.includes('申请')) return <Target className="h-4 w-4" />
    if (event.includes('分配')) return <Users className="h-4 w-4" />
    if (event.includes('完成')) return <CheckCircle className="h-4 w-4" />
    if (event.includes('休眠')) return <Clock className="h-4 w-4" />
    return <Activity className="h-4 w-4" />
  }

  return (
    <Card>
      <CardHeader>
        <CardTitle className="flex items-center space-x-2">
          <ArrowRight className="h-5 w-5" />
          <span>状态流转操作</span>
        </CardTitle>
      </CardHeader>
      <CardContent>
        <div className="space-y-6">
          {/* 当前状态显示 */}
          <div className="flex items-center space-x-4">
            <div className="flex-shrink-0">
              <span className="text-sm font-medium text-gray-700">当前状态:</span>
            </div>
            <Badge className={cn("px-3 py-1", getStatusColor(currentStatus))}>
              {currentStatus}
            </Badge>
          </div>

          {/* 流转操作区域 */}
          {availableTransitions.length > 0 ? (
            <div className="space-y-4">
              {/* 事件选择 */}
              <div className="space-y-2">
                <Label className="text-sm font-medium text-gray-700">选择流转事件:</Label>
                <Select value={selectedEvent} onValueChange={handleEventChange}>
                  <SelectTrigger>
                    <SelectValue placeholder="请选择要执行的事件" />
                  </SelectTrigger>
                  <SelectContent>
                    {availableTransitions.map((transition) => (
                      <SelectItem key={transition.id} value={transition.id}>
                        <div className="flex items-center space-x-2">
                          {getEventIcon(transition.event)}
                          <span>{transition.event}</span>
                        </div>
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>

              {/* 目标状态显示 */}
              {selectedTransition && (
                <div className="space-y-3">
                  <div className="bg-blue-50 p-4 rounded-lg">
                    <div className="flex items-center justify-between">
                      <div className="flex items-center space-x-3">
                        <span className="text-sm font-medium text-gray-700">目标状态:</span>
                        <div className="flex items-center space-x-2">
                          <Badge className={cn("px-3 py-1", getStatusColor(selectedTransition.fromStatus))}>
                            {selectedTransition.fromStatus}
                          </Badge>
                          <ArrowRight className="h-4 w-4 text-gray-400" />
                          <Badge className={cn("px-3 py-1", getStatusColor(selectedTransition.toStatus))}>
                            {selectedTransition.toStatus}
                          </Badge>
                        </div>
                      </div>
                    </div>
                    <p className="text-sm text-gray-600 mt-2">{selectedTransition.description}</p>
                    
                    {selectedTransition.requiresApproval && (
                      <div className="mt-3 p-2 bg-blue-100 rounded text-sm text-blue-700">
                        此流转需要审核批准
                      </div>
                    )}
                    
                    {selectedTransition.requiresAttachment && (
                      <div className="mt-3 p-2 bg-orange-100 rounded text-sm text-orange-700">
                        此流转需要上传附件
                      </div>
                    )}
                  </div>

                  {/* 上传附件 */}
                  <div className="space-y-2">
                    <Label className="text-sm font-medium text-gray-700">上传附件:</Label>
                    <div className="border-2 border-dashed border-gray-300 rounded-lg p-6">
                      <input
                        type="file"
                        multiple
                        onChange={handleFileUpload}
                        className="hidden"
                        id="file-upload"
                      />
                      <label
                        htmlFor="file-upload"
                        className="cursor-pointer flex flex-col items-center justify-center"
                      >
                        <Upload className="h-8 w-8 text-gray-400 mb-2" />
                        <span className="text-sm text-gray-600">点击上传文件或拖拽文件到此处</span>
                        <span className="text-xs text-gray-500 mt-1">支持多个文件上传</span>
                      </label>
                    </div>
                    
                    {/* 已上传文件列表 */}
                    {attachments.length > 0 && (
                      <div className="space-y-2">
                        <Label className="text-sm font-medium text-gray-700">已上传文件:</Label>
                        <div className="space-y-2">
                          {attachments.map((file, index) => (
                            <div key={index} className="flex items-center justify-between p-3 bg-gray-50 rounded-lg">
                              <div className="flex items-center space-x-3">
                                <FileText className="h-5 w-5 text-gray-400" />
                                <div>
                                  <span className="text-sm font-medium">{file.name}</span>
                                  <div className="text-xs text-gray-500">
                                    ({(file.size / 1024).toFixed(1)} KB)
                                  </div>
                                </div>
                              </div>
                              <Button
                                variant="ghost"
                                size="sm"
                                onClick={() => removeAttachment(index)}
                                className="text-red-500 hover:text-red-700"
                              >
                                <X className="h-4 w-4" />
                              </Button>
                            </div>
                          ))}
                        </div>
                      </div>
                    )}
                  </div>

                  {/* 备注输入 */}
                  <div className="space-y-2">
                    <Label htmlFor="note" className="text-sm font-medium text-gray-700">备注说明:</Label>
                    <Textarea
                      id="note"
                      placeholder="请输入流转说明或备注信息..."
                      value={note}
                      onChange={(e) => setNote(e.target.value)}
                      rows={3}
                      className="resize-none"
                    />
                  </div>

                  {/* 描述输入 */}
                  <div className="space-y-2">
                    <Label htmlFor="description" className="text-sm font-medium text-gray-700">节点描述:</Label>
                    <Textarea
                      id="description"
                      placeholder="请输入此流转节点的详细描述，将作为图谱中节点的显示信息..."
                      value={description}
                      onChange={(e) => setDescription(e.target.value)}
                      rows={4}
                      className="resize-none"
                    />
                    <p className="text-xs text-gray-500">此描述将作为图谱中节点的显示信息</p>
                  </div>

                  {/* 操作按钮 */}
                  <div className="flex justify-end space-x-3 pt-4">
                    <Button
                      variant="outline"
                      onClick={() => {
                        setSelectedEvent("")
                        setSelectedTransition(null)
                        setNote("")
                        setDescription("")
                        setAttachments([])
                      }}
                    >
                      取消
                    </Button>
                    <Button
                      onClick={handleSubmit}
                      disabled={isSubmitting || (selectedTransition.requiresAttachment && attachments.length === 0)}
                      className="min-w-[100px]"
                    >
                      {isSubmitting ? '提交中...' : '确认流转'}
                    </Button>
                  </div>
                </div>
              )}
            </div>
          ) : (
            <div className="text-center py-8 text-gray-500">
              当前状态下无可执行的流转操作
            </div>
          )}
        </div>
      </CardContent>
    </Card>
  )
}